﻿using SqlSugar;
using web_api_demo101.Entities;

namespace web_api_demo101.DbContext;

public sealed class SqlSugarDbClient
{
    //private readonly SqlSugarClient DbContext;

    public static SqlSugarClient GetSqlSugarDbClient()
    {
        SqlSugarClient DbClient = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = "datasource=demo.db",
            DbType = DbType.Sqlite,
            IsAutoCloseConnection = true,
            ConfigureExternalServices = new ConfigureExternalServices()
            {
                //处理列名
                EntityService = (x, p) =>
                {
                    p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);
                },
                //处理表名
                EntityNameService = (x, p) =>
                {
                    p.DbTableName = UtilMethods.ToUnderLine(p.DbTableName);
                    p.IsDisabledDelete = true; //禁止删除
                }
            }
        }, db => {
            db.Aop.OnLogExecuting = (sql, pars) => {
                //获取原生SQL推荐 5.1.4.63  性能OK
                Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
            };
        });

        //建库
        DbClient.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库

        //DbClient.CodeFirst.Con
        //建表（看文档迁移）
        DbClient.CodeFirst.InitTables<Student>(); //所有库都支持   

        return DbClient;
    }
}
